#!/usr/bin/env python3
from sanic import Sanic, response
from sanic_mongodb_ext import MongoDbExtension
from umongo import Instance, Document
from umongo.fields import StringField
from umongo.frameworks import MotorAsyncIOInstance

app = Sanic(__name__)
# Configuration for MongoDB and uMongo
app.config.update({
    "MONGODB_DATABASE": "app", # Make ensure that the `app` database is really exists
    "MONGODB_URI": "mongodb://root:root@127.0.0.1:27017",
    # You can also specify custom connection options.
    # For more details check the official docs: https://api.mongodb.com/python/3.7.0/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient
    "MONGODB_CONNECT_OPTIONS": {
        "minPoolSize": 10,
        "maxPoolSize": 50,
    },
    "LAZY_UMONGO": MotorAsyncIOInstance(),
})
# uMongo client is available as `app.ctx.mongodb` or `app.ctx.extensions['mongodb']`.
# The lazy client will be available as `app.ctx.lazy_mongodb` only when the database was specified,
# and which is a great choice for the structured projects.
MongoDbExtension(app)


# Describe the model
@app.ctx.lazy_umongo.register
class Artist(Document):
    name = StringField(required=True, allow_none=False)


# And use it later for APIs
@app.route("/")
async def handle(request):
    artist = Artist(name="A new rockstar!")
    await artist.commit()
    return response.json(artist.dump())


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8000)